import React, { useState } from 'react';
import { useSelector } from 'react-redux';
import { Button, Dropdown, Menu } from 'antd';
import { CaretDownOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import PropTypes from 'prop-types';
import { Icon } from '../../icons';
import classnames from 'classnames';
import isDisplaySetReconstructable from '../../utils/isDisplaySetReconstructable';
import { TOOLBAR_BUTTON_TYPES } from '@ohif/core';

import './ToolbarButton.styl';

function ToolbarButton(props) {
  const [visible, setVisible] = useState(false);

  const { id, type, buttons, commandName, className, isActive, disabled, icon, onClick, activeButtons } = props;
  const { t } = useTranslation("Buttons");
  const classNames = classnames(className, 'toolbar-button', id, { active: isActive });

  const hasMenu = buttons && (buttons.length > 0);
  const hasCommand = (typeof commandName === 'string') && (commandName !== '');
  const isSetToolActive = type && type === TOOLBAR_BUTTON_TYPES.SET_TOOL_ACTIVE;

  const getIcon = icon => {
    if (icon) {
      let iconTag = null
      if (typeof icon === 'string') {
        iconTag = <Icon name={icon} />;
        // return (<Icon name={icon} />);
      } else {
        const CIcon = icon;
        iconTag = <CIcon />;
        // return (<CIcon />);
      }
      return (<div className="icon-wrap">{iconTag}</div>)
    }
    return null;
  }

  const buttonText = (button, isActive) => {
    return (isActive && button.labelWhenActive) ? button.labelWhenActive : button.label;
  }

  const buttonIcon = (button, isActive) => {
    const btnIcon = (isActive && button.iconWhenActive) ? button.iconWhenActive : button.icon;
    return getIcon(btnIcon);
  };

  const isDisabled = id => {
    if (id && id.startsWith('vtk')) {
      const { viewportSpecificData, activeViewportIndex } = useSelector(state => {
        const modeState = state.viewports[state.viewports.viewMode] || {};
        const { viewportSpecificData, activeViewportIndex } = modeState;

        return {
          viewportSpecificData,
          activeViewportIndex,
        }
      });
      return !isDisplaySetReconstructable(viewportSpecificData, activeViewportIndex);
    }

    return disabled;
  }

  const handleMenuClick = event => {
    event.domEvent.stopPropagation();
    if (onClick) {
      const newEvt = Object.assign({}, event, { source: 'menu' });
      onClick(newEvt, props);
      setVisible(false);
    }
  }

  const handleBtnClick = event => {
    event.stopPropagation();
    if (hasCommand && onClick) {
      const newEvt = Object.assign({}, event, { source: 'button' });
      onClick(newEvt, props);
    } else {
      setVisible(!visible);
    }
  }

  const handleMenuBtnClick = event => {
    event.stopPropagation();
    if (isSetToolActive && onClick) {
      const newEvt = Object.assign({}, event, { source: 'button' });
      onClick(newEvt, props);
    }
  }

  const onVisibleChange = visible => {
    setVisible(visible);
  }

  const menu = (
    <Menu onClick={handleMenuClick}>
      {
        buttons.map(b => {
          const isActive = activeButtons.includes(b.id);
          return (b.type === TOOLBAR_BUTTON_TYPES.DIVIDER) ? (
            <Menu.Divider
              key={b.id}
              className={classnames('toolbar-menu-divider', b.id, b.className)}
            />) :
            (<Menu.Item
              key={b.id}
              disabled={isDisabled(b.id)}
              className={classnames('toolbar-menu-item', b.id, b.className, { active: isActive })}
              icon={buttonIcon(b, isActive)}>
              {t(buttonText(b, isActive))}
            </Menu.Item>);
        })
      }
    </Menu>
  );
  const btn = (
    <Button
      className={classNames}
      disabled={isDisabled(id)}
      icon={buttonIcon(props, isActive)}
      onClick={handleBtnClick}
    >
      {t(buttonText(props, isActive))}
      {/* {hasMenu
        ? (<Dropdown.Button
            disabled={isDisabled(id)}
            icon={<CaretDownOutlined />}
            overlay={menu}
            trigger={['click']}
            buttonsRender={([leftButton, rightButton]) => [btn, rightButton]}
            onClick={handleBtnClick}
            onVisibleChange={onVisibleChange}
            visible={visible} />)
        : t(buttonText(id, label))
      } */}
    </Button>
  );

  const dropdownBtn = (
    <Button className={classNames} disabled={isDisabled(id)} onClick={handleBtnClick}>
      {buttonIcon(props, isActive)}
      <Dropdown
        disabled={isDisabled(id)}
        overlay={menu}
        trigger={['click']}
        onClick={handleMenuBtnClick}
        onVisibleChange={onVisibleChange}
        visible={visible}>
        <span className="dropdown-btn">
          {t(buttonText(props, isActive))}
          <CaretDownOutlined className="dropdown-btn-arrow" />
        </span>
      </Dropdown>
    </Button>
    // <Button disabled={isDisabled(id)} icon={buttonIcon(props, isActive)} onClick={handleBtnClick}>
    //   {t(buttonText(props, isActive))}
    // </Button>
  );

  return (
    <div className={classNames} id={id} key={id}>
      {/* {hasMenu?(
        <Dropdown.Button
          disabled={isDisabled(id)}
          icon={<CaretDownOutlined />}
          overlay={menu}
          trigger={['click']}
          buttonsRender={([leftButton, rightButton]) => [btn, rightButton]}
          onClick={handleBtnClick}
          onVisibleChange={onVisibleChange}
          visible={visible}
        />
      ):btn} */}
      {hasMenu ? dropdownBtn : btn}
    </div>
  );
}

ToolbarButton.propTypes = {
  id: PropTypes.string,
  isActive: PropTypes.bool,
  label: PropTypes.string.isRequired,
  labelWhenActive: PropTypes.string,
  className: PropTypes.string,
  icon: PropTypes.any,
  buttons: PropTypes.array,
  onClick: PropTypes.func,
}

ToolbarButton.defaultProps = {
  isActive: false,
  disabled: false,
  className: '',
  buttons: [],
}

export default ToolbarButton;
